﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.IO.Ports;
using System.Threading;

using HostPc;

namespace HostPc
{
    namespace HVGSerial
    {
        /**
          * Adapter处理hostpc与HVG通信的方面操作。**/
        class Adapter
        {
            public SerialPort hvg_serial_port = null;
            public AWSIOTCoreSDK.Controller awsiot_controller = null;
            public HostPc.Configuration hostpc_config = null;

            /**
             * Adapter构造函数**/
            public Adapter(ref HostPc.Configuration __hostpc_config)
            {
                hostpc_config = __hostpc_config;
                InitHVGSeriaAdapter();
                ConnectHVGSerial();

                // 如果没连接上HVG，则重连
                if (hvg_serial_port==null)
                    ReconnectHVGSerial();
                if (!hvg_serial_port.IsOpen)
                    ReconnectHVGSerial();

            } // Adapter()


            /**
             * 设置Adapter与HVG的各项参数，实例化一个serialport对象。**/
            public void InitHVGSeriaAdapter()
            {
                if (hvg_serial_port != null)
                    return;
                while (true) {
                    try
                    {
                        // 实例化一个serialport对象，并传入参数。
                        hvg_serial_port = new SerialPort();
                        hvg_serial_port.PortName = hostpc_config.port_name;
                        hvg_serial_port.BaudRate = hostpc_config.baud_rate;
                        hvg_serial_port.Parity = Parity.None;
                        hvg_serial_port.StopBits = StopBits.One;
                        hvg_serial_port.DataBits = 8;
                        hvg_serial_port.Handshake = Handshake.None;
                        break;
                    }
                    catch
                    {
                        Console.WriteLine("HVG配置错误，请重新配置！");
                        Thread.Sleep(hostpc_config.reconnect_interval_seconds);
                    }
                } // while()
                
            } // InitHVGSeriaAdapter()


            /**
             * 连接到HVG。**/
            public void ConnectHVGSerial()
            {
                if (hvg_serial_port == null)
                {
                    Console.WriteLine("暂无SerialPort实例化对象，请创建SerialPort对象！\n");
                    return;
                }

                // 尝试打开特定端口号的HVG设备
                try
                {
                    hvg_serial_port.Open();
                    Console.WriteLine("成功连接上" + hvg_serial_port.PortName + "！\n");
                }
                catch
                {
                    Console.WriteLine("不能连接到" + hvg_serial_port.PortName + "，请检查Configuration中的端口号！\n");
                    return;
                }

            } // HVGSerialConnect()


            /**
             * 尝试重连HVG设备**/
            public void ReconnectHVGSerial()
            {
                while (true)
                {
                    // 已有serial对象，重连失败
                    if (!hvg_serial_port.IsOpen)
                    {
                        InitHVGSeriaAdapter();
                        ConnectHVGSerial();
                        Thread.Sleep(hostpc_config.reconnect_interval_seconds);
                    }
                    else
                    {
                        Console.WriteLine("HVG重连成功");
                        break;
                    }
                } // while()

            } // ReconnectHVGSerial()


            /**
             * 当hostpc收到来自HVG的数据时需要使用MqttContactAwsIOT模块Publish()出去**/
            public void ReceivedHVGDataHandler(object sender, SerialDataReceivedEventArgs s)
            {
                // 若没有连接到AWSIOTcore，则重连
                if (awsiot_controller.awsiot_adapter.mqtt_client == null)
                {
                    awsiot_controller.awsiot_adapter.ReConnectAWSIOTCore();
                }
                if (!awsiot_controller.awsiot_adapter.mqtt_client.IsConnected)
                {
                    awsiot_controller.awsiot_adapter.ReConnectAWSIOTCore();
                }

                // 在有人值守和无人值守时，判断是否能发送数据
                if (awsiot_controller.awsiot_app.IsValidPublish(ref awsiot_controller.awsiot_adapter))
                {
                    try
                    {
                        string hvg_read_data = hvg_serial_port.ReadExisting();
                        awsiot_controller.awsiot_adapter.Publish(awsiot_controller.hostpc_config.topic_pub, hvg_read_data);
                        Console.WriteLine("\n收到来自HVG的数据并pub出去：" + hvg_read_data);
                    }
                    catch
                    {
                        Console.WriteLine("\n无法从HVG收到数据或者无法发送到AWSIOTCore！");
                        return;
                    }
                } // if()

            } // ReceivedHVGDataHandler()

            /**
             * 检测HVG是否连接**/
            public void DetectHVGConnected() {

                // 实现HVG方面断线重连
                while (true)
                {
                    if (hvg_serial_port == null)
                    {
                        ReconnectHVGSerial();
                        Thread.Sleep(1000);
                    }
                    if (!hvg_serial_port.IsOpen)
                    {
                        ReconnectHVGSerial();
                        Thread.Sleep(1000);
                    }
                    else {
                        Thread.Sleep(5000);
                    }

                } // while()
            }

        } // class HostPcRS232_Adapter

    } // HVGSerial

} // HostPc

